﻿using System.Xml.Linq;

namespace DiveDeeper.VsxLibrary.Core
{
  // ====================================================================================
  /// <summary>
  /// This class contains helper types for handling XDocument and related classes.
  /// </summary>
  // ====================================================================================
  public static class XObjectHelper
  {
    const string CDataPrefix = "<![CDATA[";
    const string CDataSuffix = "]]>";

    // --------------------------------------------------------------------------------
    /// <summary>
    /// Obtains the text from an XElement. The text can be the value of the stecified
    /// node or withtin a CDATA tag.
    /// </summary>
    /// <param name="node">Node to obtain the text from.</param>
    /// <returns>Value text of the node.</returns>
    // --------------------------------------------------------------------------------
    public static string GetText(XElement node)
    {
      if (node.FirstNode == null)
        return node.Value;
      XCData cdata = node.FirstNode as XCData;
      if (cdata == null) return node.FirstNode.ToString();
      string result = cdata.ToString();
      return result.Substring(CDataPrefix.Length,
        result.Length - CDataPrefix.Length - CDataSuffix.Length);
    }
  }
}
